# -*- coding: utf8 -*-

import sys
from twisted.internet import reactor
from twisted.python.log import startLogging
from twisted.internet.error import *
from pywow import realmserver, realmclient, worldserver, worldclient, errors
import time
from pywow.opcodes import opcodes

debug = False
myusername = 'kreved'
mypassword = 'matan'
myhost = '10.25.6.157'
rport = 3724
wport = 3725

startLogging(sys.stdout)

class myrealmserver(realmserver.RealmServerFactory):
 def getSV(self, username):
  u = myusername.upper()
  p = mypassword.upper()
  if username == u: return self.generateSV(u, p)
  else: raise errors.NoSuchUser, username

class myrealmclient(realmclient.RealmClientFactory):
 def onRealmList(self, realms, K):
  """получив realmlist - выбираем, к какому серверу коннектиться, и делаем это."""
  if realms:
   realm = realms[0]
   address = realm[4]
   name = realm[3]
   host, port = address.split(':')
   print "Will connect to %s (%s)" % (address, name)
   wclient.setAuthData(self.username, K)
   reactor.connectTCP(host, int(port), wclient)
  else:
   print "No realms available."

class myworldserver(worldserver.WorldServerFactory):
 def unHandledPacket(self, session, opcode, body):
  print "Unhandled %s packet, body (%s bytes) is: %s" % (opcodes[opcode], len(body), repr(body))

class myworldclient(worldclient.WorldClientFactory):
 def unHandledPacket(self, session, opcode, body):
  print "Unhandled %s packet, body (%s bytes) is: %s" % (opcodes[opcode], len(body), repr(body))
 def authDone(self, session, tbc):
  print "Authenticated on world server (tbc=%s)" % tbc

rserver = myrealmserver()
rclient = myrealmclient()
wserver = myworldserver(ip='10.25.6.157', port=wport)
wclient = myworldclient()

rclient.setAuthData(myusername, mypassword)
rserver.addRealm(wserver)
wserver.reactor = reactor

def runClient():
 reactor.connectTCP(myhost, rport, rclient)

# запускаем сервера
try:
 reactor.listenTCP(rport, rserver)
 reactor.listenTCP(wport, wserver)
except CannotListenError:
 print "Can't start servers. (CannotListenError)"

# спустя 0.1 секунду запускаем клиент
reactor.callLater(0.1, runClient)

reactor.run()
